package com.peng.rpc.netty.util;

import com.peng.rpc.entity.RpcResponse;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/3/7 15:42
 */
public class UnprocessedRequests {

    private static final Map<String, CompletableFuture<RpcResponse>> unprocessedRequests = new ConcurrentHashMap<>();

    private UnprocessedRequests() {

    }

    public CompletableFuture<RpcResponse> remove(String requestId) {
        return unprocessedRequests.remove(requestId);
    }

    public void put(String requestId, CompletableFuture<RpcResponse> responseCompletableFuture) {
        unprocessedRequests.put(requestId, responseCompletableFuture);
    }

    public void complete(RpcResponse rpcResponse) {
        CompletableFuture<RpcResponse> responseFuture = remove(rpcResponse.getRequestId());
        if (responseFuture != null) {
            responseFuture.complete(rpcResponse);
        } else {
            throw new IllegalStateException("响应消息获取失败");
        }
    }

}
